
package com.radioapp.liaoliaobao.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jaydenxiao.common.base.BaseActivity;
import com.jaydenxiao.common.baseapp.BaseApplication;
import com.jaydenxiao.common.basebean.LoginEvent;
import com.jaydenxiao.common.baserx.RxSubscriber;
import com.jkb.fragment.rigger.annotation.Puppet;
import com.radioapp.liaoliaobao.R;
import com.radioapp.liaoliaobao.bean.PageBean;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.trello.rxlifecycle2.components.support.RxFragment;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import me.jessyan.autosize.utils.LogUtils;

/**
 * 列表数据Fragment
 */
@Puppet
public abstract class BaseRiggerRecyclerFragment<T> extends RxFragment {

    /**
     * 刷新控件
     **/
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout mRefresh;

    @BindView(R.id.recyclerView)
    RecyclerView mRecycler;

    /**
     * 页面状态
     **/
  /*  @BindView(R.id.emptyLayout)
    protected EmptyLayout mEmptyLayout;*/


    protected Activity mActivity;
    protected Context mContext;

    protected View mView;
    private Unbinder bind;

    protected int page = 1;       //页数
    private BaseQuickAdapter<T, BaseViewHolder> mAdapter;


    /**
     * 存储网络请求.
     **/
    private CompositeDisposable mCompositeDisposable = null;

    protected int getLayoutResource() {
        return R.layout.fragment_base_recycler;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = getActivity();
        mContext = getContext();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        unSubscribe();
        mActivity = null;
        mContext = null;
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        handIntent(savedInstanceState == null ? getArguments() : savedInstanceState);
        mView = inflater.inflate(getLayoutResource(), container, false);
        bind = ButterKnife.bind(this, mView);

        initView();
        return mView;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (bind != null)
            bind.unbind();
        if (mCompositeDisposable != null)
            mCompositeDisposable.clear();
    }

    private void initView() {
        initData();
        initRefresh();
        initAdapter();
        request(getUrl(page));
    }

    /**
     * 设置可以刷新的请求的参数
     **/
    public void setRefreshParams() {
        page = 1;
        request(getUrl(page));
    }

    /**
     * 初始化刷新
     **/
    private void initRefresh() {
        //设置刷新颜色
//        mRefresh.setColorSchemeResources(R.color.colorPrimary);
        mRefresh.setOnRefreshListener(refreshLayout -> {
            if (refreshLayout != null)
                refreshLayout.finishRefresh();
            page = 1;

            request(getUrl(page));
        });
    }

    /**
     * 初始化Adapter
     **/
    private void initAdapter() {
        mAdapter = getAdapter();
        mRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecycler.setAdapter(mAdapter);
        //Adapter加载动画
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(true);
        //Adapter加载更多
        mAdapter.setOnLoadMoreListener(() -> mRecycler.post(() -> {
            request(getUrl(page));
        }), mRecycler);
    }

    /**
     * 请求网络数据
     **/
    @SuppressWarnings("AccessStaticViaInstance")
    private void request(Observable<PageBean<T>> observable) {
        if (observable == null) return;
        observable.subscribe(new RxSubscriber<PageBean<T>>(mActivity, true) {
            @Override
            protected void subscribe(Disposable d) {
                addSubscribe(d);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                try {
                    if (page > 1) {
                        if (!mAdapter.getData().isEmpty()) {
                            mAdapter.loadMoreEnd();
                        }
                    } else {
                        //  mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                        mAdapter.loadMoreFail();
                    }

                } catch (Exception e1) {
                    e.printStackTrace();
                    // mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                    mAdapter.loadMoreFail();
                }

            }

            @Override
            protected void _onNext(PageBean<T> tPageBean) {
                onSuccess(tPageBean);
            }

            @Override
            protected void _TokenInvalid() {
                if (mActivity instanceof BaseActivity) {
                    ((BaseActivity) mActivity).tokenInvalid();
                }
            }
        });

    }

    /**
     * 数据请求成功
     **/
    private void onSuccess(PageBean<T> t) {

        // pageCount=t.getCurrent_page();//总页数

        if (t.getCurrent_page() == 1) {

            page++;
            mAdapter.setNewData(t.getData());
            mAdapter.loadMoreComplete();

        } else {
            if (t.getData().size() == 0 && t.getData().size() < 10) {
                mAdapter.loadMoreEnd();
            } else {
                page++;
                mAdapter.addData(t.getData());
                mAdapter.loadMoreComplete();
            }
        }

    }

    /**
     * 点击刷新
     **/
  /*  @OnClick(R.id.emptyLayout)
    void onRefresh(){
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        request(getUrl(page));
    }
*/
    protected void addSubscribe(Disposable disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);
    }

    protected void unSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();//保证activity结束时取消所有正在执行的订阅
        }
    }


    protected abstract void initData();

    protected abstract BaseQuickAdapter<T, BaseViewHolder> getAdapter();

    protected abstract Observable<PageBean<T>> getUrl(int pageNo);

    public void handIntent(Bundle bundle) {
    }

    /**
     * 用这个的话必须要在token刷新到时候调用
     */
    protected void tokenRefresh() {
        getUrl(1);
    }


    //首页中点击新手回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void newsClick(LoginEvent event) {
        tokenRefresh();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtils.e("fragment状态--》"+isVisibleToUser);
    }



}
